<?php

namespace App\Services;


class Certificate
{
    // 更新身份信息
    public static function upCertInfo($params, &$msg='')
    {
        $api_url = env('CERT_API_URL').'/api/certificate/update';

        $post_data['id_card_name'] = $params['consignee'];
        $post_data['id_card_number'] = $params['nric'];
        $post_data['id_card_front'] = $params['card1'];
        $post_data['id_card_reverse'] = $params['card2'];
        $app_key = env('CERT_TOKEN');
        $post_data['sign'] = self::encrypt($post_data, $app_key);

        $res = self::sendPost($api_url, $post_data);
        // dd($post_data, $res);

        if ($res['code'] == '0' && $res['msg']=='操作成功')
        {
            return true;
        }
        else
        {
            $msg = $res['data']['msg'];
            return false;
        }
    }

    // 查询身份信息
    public static function checkCert($params, &$msg='')
    {
        $api_url = env('CERT_API_URL').'/api/certificate/check';

        $post_data['id_card_number'] = $params['nric'];
        $app_key = env('CERT_TOKEN');
        $post_data['sign'] = self::encrypt($post_data, $app_key);
        $res = self::sendPost($api_url, $post_data);
        // dd($post_data, $res);

        if ($res['code'] == '0' && $res['data']['status']=='1')
        {
            return true;
        }
        else
        {
            $msg = $res['data']['msg'];
            return false;
        }
    }

    public static function sendPost($url, $data)
    {
        // dd($url, $data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($res, 1);
        return $res;
    }

    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    public static function encrypt($params, $signKey='')
    {
        ksort($params);

        $paramString = '';

        foreach ($params as $key => $value)
        {
            if (is_null($value) || $value == '' || $key == 'sign') {
                continue;
            }

            $paramString .= trim($key) . '=' . trim($value) . '&';
        }

        $paramString = substr($paramString, 0, -1);

        // $signKey = 'base64:Wfxt/ngwZJ9KcAfpiZgPk3XH2f+f0ocyPFuDJRe3mgM=';

        $sha1 = hash_hmac("sha1", $paramString, $signKey, $raw_output = TRUE);

        $sign = base64_encode($sha1);

        return $sign;
    }
}
